import { ref, reactive } from "vue";
import type { FormInstance, FormRules } from "element-plus";

interface UseFormOptions<T> {
  initialForm: T;
  rules?: FormRules;
}

export function useForm<T extends object>(options: UseFormOptions<T>) {
  const formRef = ref<FormInstance>();
  const form = reactive({ ...options.initialForm });
  const rules = ref<FormRules>(options.rules || {});
  const originalForm = ref<T>(options.initialForm ? JSON.parse(JSON.stringify(options.initialForm)) : ({} as T));

  // 清理空值字段
  const cleanForm = (valuesToFilter: any[] = ["", null, undefined]) => {
    return Object.fromEntries(Object.entries(form).filter(([, val]) => !valuesToFilter.includes(val)));
  };

  // 重置表单
  const resetForm = () => {
    Object.assign(form, JSON.parse(JSON.stringify(originalForm.value))); // 注意这里需要 .value
    formRef.value?.clearValidate();
  };

  // 设置表单数据
  const setForm = (data: Partial<T>) => {
    Object.assign(form, data);
  };

  // 表单验证
  const validate = (options?: { cleanBeforeResolve?: boolean }): Promise<T> => {
    return new Promise((resolve, reject) => {
      if (!formRef.value) return reject("formRef is not defined");
      formRef.value.validate((valid, fields) => {
        if (valid) {
          if (options?.cleanBeforeResolve) {
            resolve(cleanForm() as T); // 清理后返回
          } else {
            resolve(form as T);
          }
        } else {
          reject(fields);
        }
      });
    });
  };

  const validateField = (field: keyof T) => {
    return formRef.value?.validateField(field as string);
  };

  return {
    formRef,
    form,
    rules,
    resetForm,
    setForm,
    cleanForm,
    validate,
    validateField
  };
}
